<template>
<!-- 搜索内容 -->
	<el-card>
		<el-form :model="searchWorkorderForm" inline>
			<el-form-item label="工单编码" style="width:240px">
				<el-input v-model="searchWorkorderForm.productionOrderCode" placeholder="工单编码"/>
			</el-form-item>
			<el-form-item label="工单名称" style="width:240px">
				<el-input v-model="searchWorkorderForm.productionOrderName" placeholder="工单名称"/>
			</el-form-item>
			<el-form-item label="来源单据" style="width:240px">
        <el-select
            v-model="searchWorkorderForm.productionOrderSource"
            filterable
            allow-create
            default-first-option
            :reserve-keyword="false"
            placeholder="来源单据"
            style="width: 240px"
        >
          <el-option label="客户订单" value="1"/>
          <el-option label="库存订阅" value="2"/>
        </el-select>
			</el-form-item>
			<el-form-item label="产品编号" style="width:240px">
				<el-input v-model="searchWorkorderForm.materialCode"/>
			</el-form-item>
			<el-form-item label="产品名称" style="width:240px">
				<el-input v-model="searchWorkorderForm.materialName"/>
			</el-form-item>
			<el-form-item label="客户编码" style="width:240px">
				<el-input v-model="searchWorkorderForm.customerCode"/>
			</el-form-item>
			<el-form-item label="客户名称" style="width:240px">
				<el-input v-model="searchWorkorderForm.customerName"/>
			</el-form-item>
			<el-form-item label="需求日期" style="width:240px">
				<el-date-picker
				        v-model="searchWorkorderForm.requestDate"
				        type="date"
				        placeholder="需求日期"
				        :disabled-date="disabledDate"
				        :shortcuts="shortcuts"
				        :size="size"
				      />
			</el-form-item>
			<!-- 操作功能:搜索与重置表单 -->
			<el-form-item>
				<el-button size="small" type="info" @click="handleSearchWorkorder">搜索工单</el-button>
				<el-button size="small" type="primary" @click="handleRestWorkorder">重置工单</el-button>
			</el-form-item>
		</el-form>
  </el-card>


 <!-- 列表 -->
 <el-card>
		<el-card>
			<el-table
			:data="workorderList"
			border
			stripe
			@selection-change="handleSelectionChange"
			>
				<el-table-column property="productionOrderCode" label="工单编码" >
          <template #default="scope">
            <el-link type="primary" :underline="false" @click="handleCodeClick(scope.row)">
              {{ scope.row.productionOrderCode}}
            </el-link>
          </template>
        </el-table-column>
				<el-table-column property="productionOrderName" label="工单名称"></el-table-column>
				<el-table-column property="productionOrderType" label="工单类型">
					<template #default="scope">
						{{scope.row.productionOrderType === 1 ? '自产' :
						scope.row.productionOrderType === 2 ? '外协' : '外购' }}
					</template>
        </el-table-column>
				<el-table-column property="productionOrderSource" label="工单来源">
					<template #default="scope">
						{{scope.row.productionOrderSource === 1 ? '客户订单' : '库存备货' }}
					</template>
        		</el-table-column>
				<el-table-column property="orderCode" label="订单编号"></el-table-column>
				<el-table-column property="materialCode" label="产品编号"></el-table-column>
				<el-table-column property="material.name" label="产品名称"></el-table-column>
				<el-table-column property="material.unit.specification" label="规格型号"></el-table-column>
				<el-table-column property="material.unit.name" label="单位"></el-table-column>
				<el-table-column property="productionOrderQuantity" label="工单数量"></el-table-column>
				<el-table-column property="prouctionOrderCode" label="调整数量"></el-table-column>
				<el-table-column property="producedQuantity" label="已生产数量"></el-table-column>
				<el-table-column property="customerCode" label="客户编码"></el-table-column>
				<el-table-column property="customer.name" label="客户名称"></el-table-column>
				<el-table-column property="requestDate" label="需求日期"></el-table-column>
				<el-table-column property="status" label="单据状态">
          <template #default="scope">
            {{scope.row.status === 1 ? '草稿' :
              scope.row.status === 2 ? '已确认' : '已审核' }}
          </template>
        </el-table-column>

			</el-table>
		</el-card>
	</el-card>

  <!-- 分页信息 -->
  <div class="demo-pagination-block">
    <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout="sizes, prev, pager, next"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>

  <el-dialog v-model="dialogProscheduleFormVisible" title="生产排产" width="800">
    <el-form :model="dialogInfoList" inline>
      <el-form-item label="工单编号">
        <el-input v-model="dialogInfoList.productionOrderCode" readonly />
      </el-form-item>
      <el-form-item label="工单名称">
        <el-input v-model="dialogInfoList.productionOrderName" readonly />
      </el-form-item>
      <el-form-item label="来源类型">
        <el-input v-model="dialogInfoList.productionOrderSource" readonly />
      </el-form-item>
      <el-form-item label="图片" >
        <el-input v-model="dialogInfoList.qrCodeUrl" readonly />
      </el-form-item>
      <el-form-item label="订单编号" v-if="dialogInfoList.orderCode">
        <el-input v-model="dialogInfoList.productionOrderType" readonly />
      </el-form-item>
      <el-form-item label="工单类型">
        <el-input v-model="dialogInfoList.productionOrderType" readonly />
      </el-form-item>
      <el-form-item label="产品编号">
        <el-input v-model="dialogInfoList.materialCode" readonly />
      </el-form-item>
      <el-form-item label="产品名称">
        <el-input v-model="dialogInfoList.material.name" readonly />
      </el-form-item>
      <el-form-item label="规格型号">
        <el-input v-model="dialogInfoList.material.specification" readonly />
      </el-form-item>
      <el-form-item label="单位">
        <el-input v-model="dialogInfoList.material.unit.name" readonly />
      </el-form-item>
      <el-form-item label="工单数量">
        <el-input v-model="dialogInfoList.productionOrderQuantity" readonly />
      </el-form-item>
      <el-form-item label="需求日期">
        <el-input v-model="dialogInfoList.requestDate" readonly />
      </el-form-item>
      <el-form-item label="客户编码">
        <el-input v-model="dialogInfoList.customer.code" readonly />
      </el-form-item>
      <el-form-item label="客户名称">
        <el-input v-model="dialogInfoList.customer.name" readonly />
      </el-form-item>
      <el-form-item label="供应商编码">
        <el-input v-model-value="dialogInfoList.supplier ? dialogInfoList.supplier.code:''" readonly />
      </el-form-item>
      <el-form-item label="供应商名称">
       <el-input :model-value="dialogInfoList.supplier ? dialogInfoList.supplier.name : ''" readonly />
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="dialogInfoList.remark" readonly />
      </el-form-item>
    </el-form>

    <!-- 工艺显示 -->
    <el-tabs type="border-card">
      <el-tab-pane v-for="workList in workFlowProcessList"
          :key="workList.id"
          :label="workList.workflowName"
      >
        <el-tabs type="border-card" @tab-change="handleTabChange" >
          <el-tab-pane v-for="processList in workList.processList"
                         :key="processList.id"
                         :label="processList.processName"
                         :name="processList.id"
            >
            <el-button size="default" type="success" @click="handleAddProductTask(processList.id)" >新增</el-button>
            <el-button size="default" type="danger" @click="handleBatchDelete" :disabled="selectedTasks.length === 0">批量删除</el-button>
            <el-table :data="productionTaskList" style="width: 100%" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" />
              <el-table-column property="taskCode" label="任务编号" width="120"/>
              <el-table-column property="taskName" label="任务名称" width="120"/>
              <el-table-column property="workstationId" label="工作站编号" width="120"/>
              <!--<el-table-column property="workstation_name" label="工作站名称" width="120"/>-->
              <el-table-column property="processId" label="工序编号" width="120"/>
              <el-table-column label="物资编码" width="120"/>
              <el-table-column property="plannedQuantity" label="排产数量" width="120"/>
              <el-table-column property="completedQuantity" label="已生产数量" width="120"/>
              <el-table-column property="startTime" label="开始生产时间" width="120"/>
              <el-table-column property="durationHours" label="生产时长" width="120"/>
              <el-table-column property="endTime" label="预计完成时间" width="120"/>
              <el-table-column property="colorCode" label="显示颜色" width="120"/>
              <el-table-column property="action" label="操作" width="120">
                <template #default="scope">
                  <el-button size="default" type="warning" @click="handleEditProductTask(scope.row)">修改</el-button>
                  <el-button size="default" type="danger" @click="handleDeleteProductTask(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            </el-tab-pane>
        </el-tabs>
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogProscheduleFormVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 添加/编辑生产任务 -->
  <el-dialog v-model="dialogAddProductTaskFormVisible" :title="isEditMode?'编辑生产任务':'添加生产任务'" width="1200">
    <el-form :model="productionTaskData" inline>
      <el-form-item label="任务编号" style="width:240px" >
        <el-input v-model="productionTaskData.taskCode" autocomplete="off" />
      </el-form-item>
      <el-form-item label="任务名称" style="width:240px" >
        <el-input v-model="productionTaskData.taskName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="工作站" style="width:240px" >
        <el-input v-model="productionTaskData.workstationId" autocomplete="off" />
      </el-form-item>
      <el-form-item  >
        <el-button type="default" size="default" @click="handleSearchWorkStationInfo"/>
      </el-form-item>
      <el-form-item label="颜色" style="width:240px" >
        <el-input v-model="productionTaskData.colorCode" autocomplete="off" />
      </el-form-item>
      <el-form-item label="排产数量" style="width:240px" >
        <el-input v-model="productionTaskData.plannedQuantity" autocomplete="off" />
      </el-form-item>
      <el-form-item label="开始时间" style="width:240px" >
        <el-input v-model="productionTaskData.startTime" autocomplete="off" />
      </el-form-item>
      <el-form-item label="生产时长" style="width:240px" >
        <el-input v-model="productionTaskData.durationHours" autocomplete="off" />
      </el-form-item>
      <el-form-item label="完成时间" style="width:240px" >
        <el-input v-model="productionTaskData.endTime" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="restProductionTaskData">取消</el-button>
        <el-button type="primary" @click="dialogAddOrUpdateProductTask">
          确认添加生产任务
        </el-button>
      </div>
    </template>
  </el-dialog>

<!-- 选择工作站弹窗 -->
  <el-dialog v-model="workstationDialogVisible" title="选择工作站" width="1200" center>
    <el-table 
      :data="workstationTaskList" 
      style="width: 100%" 
      @row-click="handleWorkstationRowClick"
      highlight-current-row
      ref="workstationTableRef">
      <!-- 单选列 -->
      <el-table-column width="55" align="center">
        <template #default="scope">
          <el-radio
              v-model="selectedWorkstationId"
              :label="scope.row.id"
              @change="handleWorkstationSelect(scope.row)">
            <span></span>
          </el-radio>
        </template>
      </el-table-column>
      <el-table-column property="code" label="工作站编号" width="120" />
      <el-table-column property="name" label="工作站名称" width="120" />
      <el-table-column property="location" label="工作站地点" width="120" />
      <el-table-column property="description" label="备注" width="120" />
      <el-table-column property="status" label="状态" width="120">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancelWorkstationSelect">取消</el-button>
        <el-button type="primary" @click="confirmWorkstationSelect" :disabled="!selectedWorkstation">
          确认选择
        </el-button>
      </div>
    </template>
  </el-dialog>




</template>

<script setup>
	import { onMounted,reactive, ref, computed, watch } from 'vue';
	import { ElMessage, ElMessageBox } from 'element-plus';
  import {getProductionOrderAllInfo, getStatus,getAllWorkFlowProcessByProductCode} from "@/api/proschedule.js";
  import {
    getProductionTaskList,
    getProductionTaskById,
    addProductionTask,
    updateProductionTask,
    deleteProductionTask,
    batchDeleteProductionTasks
  } from "@/api/productionTask.js";

  import {getWorkstationByProcessId} from "@/api/workstation.js";  //查询工作站

  // 搜索表单
	const searchWorkorderForm = ref({
    id:"",
    productionOrderCode:"",
		productionOrderName:"",
		productionOrderSource:"",
		materialCode:"",
		materialName:"",
		customerCode:"",
		customerName:"",
		requestDate:"",
	});

  // 重置搜索表单所有字段
    const handleRestWorkorder = () => {
    searchWorkorderForm.value = {
      productionOrderCode: "",
      productionOrderName: "",
      productionOrderSource: "",
      materialCode: "",
      materialName: "",
      customerCode: "",
      customerName: "",
      requestDate: "",
    };
    handleSearchWorkorder();
  }

  // 分页数据
	const pagination = ref({
	  currentPage: 1,
	  pageSize: 10,
	  total: 0
	});

	// 数据表单
	const workorderList = ref([]);

	//搜索表单
	const handleSearchWorkorder = () =>{
		const queryParams = {
			page: pagination.value.currentPage,
			pageSize: pagination.value.pageSize,
			...searchWorkorderForm.value
   		 };

    getStatus(queryParams).then(res=>{
			workorderList.value = res.data.list;
			pagination.value.total = res.data.total;
		});
	}

	// 改变分页大小
	const handleSizeChange = (newSize) =>{
		pagination.value.pageSize = newSize;
		pagination.value.currentPage = 1;
		handleSearchWorkorder();
	}

	// 改变当前页码
	const handleCurrentChange =(newPage)=>{
		pagination.value.currentPage = newPage;
		handleSearchWorkorder();
	}


  // ====================== 弹窗 ======================

  const dialogProscheduleFormVisible = ref(false);

  // 信息展示（提供安全的默认结构，避免模板 v-model 读取 undefined）
  const dialogInfoList = ref({
    id:"",
    productionOrderCode: '',
    productionOrderName: '',
    productionOrderSource: '',
    orderCode: '',
    productionOrderType: '',
    materialCode: '',
    productionOrderQuantity: '',
    requestDate: '',
    remark: '',
    qrCodeUrl: '',
    material: { name: '', specification: '', unit: { name: '' } },
    customer: { code: '', name: '' },
    supplier: { code: '', name: '' },
  });


  const workFlowProcessList = ref([]);

  // ====================== 点击跳转 =========================
  const handleCodeClick =(row)=>{
    dialogProscheduleFormVisible.value = true;

    console.log(row.id);
    //根据id获取对应的工单的详细信息
    getProductionOrderAllInfo(row.id).then(res=>{
      dialogInfoList.value = res.data
    })

    getAllWorkFlowProcessByProductCode(row.materialCode).then(res=>{
      console.log(res.data)
      workFlowProcessList.value = res.data;
    })
  }


  // ====================== 加载工艺对应的工序等内容 =========================
  // 分页信息
  const paginationTask = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0
  });

  const productionTaskList = ref([]);
  
  // 当前选中的工序ID
  const currentProcessId = ref(null);
  
  // 批量删除相关
  const selectedTasks = ref([]);

  const productionTaskData = ref({
    id:"",
    taskCode:"",
    taskName:"",
    productionOrderId:"",
    workstationId:"",
    processId:"",
    materialCode:"",
    plannedQuantity:"",
    completedQuantity:"",
    startTime:"",
    endTime:"",
    durationHours:"",
    status:"",
    colorCode:"",
  })

  // 重置表单数据
  const restProductionTaskData = () => {
    productionTaskData.value = {
      id:"",
      taskCode:"",
      taskName:"",
      productionOrderId:"",
      workstationId:"",
      processId:"",
      materialCode:"",
      plannedQuantity:"",
      completedQuantity:"",
      startTime:"",
      endTime:"",
      durationHours:"",
      status:"",
      colorCode:"",
    }
    isEditMode.value = false;
    dialogAddProductTaskFormVisible.value = false;
  }
  

  //监听当前选择的对应工艺的工序的id   
  const handleTabChange = (processId) => {
    // 保存当前工序ID
    currentProcessId.value = processId;
    productionTaskData.value.processId = processId;
    productionTaskData.value.materialCode = dialogInfoList.value.materialCode;
    productionTaskData.value.productionOrderId =dialogInfoList.value.id;
    getProductionTaskList(dialogInfoList.value.id, processId, paginationTask.value.currentPage, paginationTask.value.pageSize).then(res=>{
      productionTaskList.value = res.data.list;
      paginationTask.value.total = res.data.total;
      console.log('查询参数:', {
        productionOrderId: dialogInfoList.value.id,
        processId: processId,
        page: paginationTask.value.currentPage,
        pageSize: paginationTask.value.pageSize
      });
      console.log('查询结果:', res.data);
    })
  }


  // =========================== 添加生产任务 ====================================
  const isEditMode = ref(false);

  // 添加生产任务弹窗
  const dialogAddProductTaskFormVisible = ref(false);

  // 添加生产任务弹窗
  const handleAddProductTask = (processId) => {
    // 检查是否有工单信息
    if (!dialogInfoList.value.id) {
      ElMessage.error('请先选择一个生产工单！');
      return;
    }
    
    // 设置必要字段
    productionTaskData.value.processId = processId;
    productionTaskData.value.materialCode = dialogInfoList.value.materialCode;
    productionTaskData.value.productionOrderId = dialogInfoList.value.id;
    
    isEditMode.value = false;
    dialogAddProductTaskFormVisible.value = true;
  }

  // 根据编辑 取出对应的 任务信息
  const handleEditProductTask = (row) => {
    isEditMode.value = true;
    dialogAddProductTaskFormVisible.value = true;
    console.log(row.id)
    getProductionTaskById(row.id).then(res=>{
      productionTaskData.value = res.data;
    })
  }

  // 添加/编辑生产任务
  const dialogAddOrUpdateProductTask = () => {
    const apiCall = isEditMode.value ? updateProductionTask(productionTaskData.value) : addProductionTask(productionTaskData.value);
    const successMessage = isEditMode.value ? "更新成功" : "添加成功";
    const errorMessage = isEditMode.value ? "更新失败" : "添加失败";
    
    // 保存processId，因为restProductionTaskData会重置它
    const currentProcessId = productionTaskData.value.processId;
    
    apiCall.then(res => {
      ElMessage.success(successMessage);
      // 先关闭弹窗和重置表单
      restProductionTaskData();
      // 然后刷新当前工序的任务列表
      handleTabChange(currentProcessId);
    }).catch(err => {
      ElMessage.error(errorMessage);
    });
  }


  const handleDeleteProductTask = (row) => {
    ElMessageBox.confirm('确定要删除这个生产任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      deleteProductionTask(row.id).then(res => {
        if(res.code == 200) {
          ElMessage.success('删除成功');
          // 刷新当前工序的任务列表 - 使用当前工序ID或行的工序ID
          const processIdToRefresh = currentProcessId.value || row.processId;
          if (processIdToRefresh) {
            handleTabChange(processIdToRefresh);
          }
        } else {
          ElMessage.error(res.message || '删除失败');
        }
      }).catch(err => {
        console.error('删除失败:', err);
        ElMessage.error('删除失败');
      });
    }).catch(() => {
      // 用户取消删除
    });
  }

  // 处理表格选择变化
  const handleSelectionChange = (selection) => {
    selectedTasks.value = selection;
  }

  // 批量删除生产任务
  const handleBatchDelete = () => {
    if (selectedTasks.value.length === 0) {
      ElMessage.warning('请先选择要删除的任务');
      return;
    }

    ElMessageBox.confirm(`确定要删除选中的 ${selectedTasks.value.length} 个生产任务吗？`, '批量删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const taskIds = selectedTasks.value.map(task => task.id);
      
      batchDeleteProductionTasks(taskIds).then(res => {
        if(res.code == 200) {
          ElMessage.success(`成功删除 ${selectedTasks.value.length} 个任务`);
          // 清空选择
          selectedTasks.value = [];
          // 刷新当前工序的任务列表
          if (currentProcessId.value) {
            handleTabChange(currentProcessId.value);
          }
        } else {
          ElMessage.error(res.message || '批量删除失败');
        }
      }).catch(err => {
        console.error('批量删除失败:', err);
        ElMessage.error('批量删除失败');
      });
    }).catch(() => {
      // 用户取消删除
    });
  }

  //=========================== 添加工作站信息 ====================================
  //选择工作站弹窗
  const workstationDialogVisible = ref(false);
  const workstationTaskList = ref([]);
  
  // 选中的工作站
  const selectedWorkstation = ref(null);
  const selectedWorkstationId = ref(null);
  const workstationTableRef = ref(null);

  //数据加载
  const handleSearchWorkStationInfo =()=>{
    workstationDialogVisible.value = true;
    getWorkstationByProcessId(2).then(res=>{
      workstationTaskList.value = res.data;
    })
  }

  // 工作站单选处理函数
  const handleWorkstationSelect = (row) => {
    selectedWorkstation.value = row;
    selectedWorkstationId.value = row.id;
  };

  // 行点击处理
  const handleWorkstationRowClick = (row) => {
    selectedWorkstation.value = row;
    selectedWorkstationId.value = row.id;
  };

  // 确认选择工作站
  const confirmWorkstationSelect = () => {
    if (selectedWorkstation.value) {
      //回填数据
      productionTaskData.value.workstationId = selectedWorkstationId.value;
      // 关闭弹窗
      workstationDialogVisible.value = false;
      
      // 清空选择
      selectedWorkstation.value = null;
      selectedWorkstationId.value = null;
    }
  };

  // 取消选择工作站
  const cancelWorkstationSelect = () => {
    selectedWorkstation.value = null;
    selectedWorkstationId.value = null;
    workstationDialogVisible.value = false;
  };


  onMounted(() => {
    handleSearchWorkorder();
  });
</script>

<style scoped>

</style>